package top.malaoshi.web.utils;

import javax.servlet.http.HttpServletRequest;

public class WebServerUtil {
    /**
     * 获取当前服务的url
     * @param request
     * @return 返回格式  协议://域名:端口号/上下文
     */
    public static String getUrl(HttpServletRequest request){
        // 拼装服务器协议域名
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();

        String server = String.format("%s://%s:%s", scheme,serverName,serverPort);
        return server;
    }

    /**
     * 获取当前服务的url，后面带有上下文
     * @param request
     * @return 返回格式  协议://域名:端口号/上下文
     */
    public static String getUrlContext(HttpServletRequest request){
        // 拼装服务器协议域名
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String contextPath = request.getContextPath();

        String server = String.format("%s://%s:%s/contextPath", scheme,serverName,serverPort);
        return server;
    }

    /**
     * 根据请求协议获取默认端口号
     * @param scheme
     * @param port
     * @return
     */
    public static int getPort(String scheme, int port) {
        if (port == -1) {
            if ("http".equals(scheme) || "ws".equals(scheme)) {
                port = 80;
            }
            else if ("https".equals(scheme) || "wss".equals(scheme)) {
                port = 443;
            }
        }
        return port;
    }

}
